let app = getApp()
var {
    Api
} = require('../../../api/api')
Page({

    /**
     * 页面的初始数据
     */
    data: {
       
      x: 0,
      y: 0,
      scale: 2,

        subjectInfo:{},
        durTime:0,
        isNext: false,
        optionJson: [],
        questionInfo2:{},
        showMoreMask: false,
        showBigMask: false,
        zid: '',//章节id
        kid: '',//课程id
        tid: '',//题库id=========这三个都是正常刷题进来的
        mock_class_id: '',
        vague: false,//是否模糊
        submit: false,//是否提交
        card: true,//答题卡是否有type为4时不展示为2也不展示3也不显示
        ye: false,//是否为夜间模式
        show: false,//答题卡是否出来
        tabid: 0,//多问的时候用的着，type=3和5
        questionNumber: 0,//用来记录当前可以跳转到哪道题
        items: [],//题目id列表
        // num: 0,//题目id索引
        num: 0,//题目id索引
        detail: '',//题目详情
        type: 1,//1为章节列表进的2就是考试//3為错题本进来的//4是直接重笔记本里和考同学进来的，将会直接显示答案
        comment: [],//评论列表
        subject: [],//笔记列表
        my_answer: [],//我选择的答案
        daitem: [],//题卡信息
        items2: [],//用来储存考试的信息
        paperInfo: [], //试卷信息
        reque: false,//是否提交中
        domain: Api.domain,
        baseShow:{},
        items3:[],//错题集
       

        countdown: '',
        endDate: '2022-05-12 18:00:00', //结束时间
        days: '00', //天
        hours: '00', //时
        minutes: '00', //分
        seconds: '00', //秒
        jsq_no: true, // 计时器开关

        reportId: 0,//答题报告id
        questionList: [],//题目列表
        questionInfo: {},//用户与题库关系
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad:async function  (options) {
        // wx.enableAlertBeforeUnload({
        //   message: "考试过程中退出将不会记录答题信息且自动交卷，确定退出吗？",
        //   success: function (res) {

        //   },
        //   fail: function (errMsg) {
        //     return false
        //   },
        // });
        if(options.type == 1){  //未生成答题卡
          console.log('wwwwwwww888889999998888899889',options);
          app.time1 = this.getNowTime()//获取考试开始时间
          this.setData({
              num: 0,
              type: 2,
              reportId: options.rid || 0,
              questionId: options.mid || 0,
              card: false,
             baseShow:await wx.$getBase()
          }, () => {
              // this.examination(options.mid)
              // this.get_paperInfo(options.mid)
              this.get_mk_sheet_info();
          })
        }
        if (options.type == 2) {//随机进来的开始考试

            console.log('ddddddddddddd555555',options);
            app.time1 = this.getNowTime()//获取考试开始时间
            this.setData({
                num: 0,
                type: 2,
                reportId: options.rid || 0,
                questionId: options.mid || 0,
                card: false,
               baseShow:await wx.$getBase()
            }, () => {
                // this.examination(options.mid)
                // this.get_paperInfo(options.mid)
                this.get_mk_sheet_info();
            })
        }
        if (options.type == 3) {//错题本进来的
            this.setData({
                num: Number(options.num),
                zid: options.zid,
                tid: options.tid,
                kid: options.kid,
                type: 3,
                card: false
            })
            this.wrongTopic()
        }

        if (options.type == 4) {//笔记本详情和分享页面进来的
            this.setData({
                num: 0,
                items: [options.id],
                submit: true,
                type: 4,
                card: false
            })
            this.tidetail()
        }

        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })

    },

    touchmoves(e){
      console.log("11111111111");
    },
    handleImageMove(e) {
      console.log("4545rt34e3434");
      let { clientX: x, clientY: y } = e.touches[0];
      this.setData({ x, y });
    },

    countDown(report_id,end_time) {
        const _this = this;
        if (!this.data.jsq_no) {
            return false
        }

        let flagTime = wx.getStorageSync(`mold_end_time_${report_id}`)
        let nowTime = new Date().getTime();
        let endTime = new Date(end_time.replace(/-/g,'/')).getTime();
        let durTime = _this.data.durTime;
        let diffTime = endTime - nowTime; //时间差
        if (flagTime){
            //继续啊
            durTime = flagTime;
        }else if (durTime<=0){
            //考试结束
            this.setData({
                countdown: '考试时间已到',
                jsq_no: false
            })
            wx.showToast({
                title:'考试时间已到',
                icon:'none',
                success(res) {
                    setTimeout(()=>{
                        _this.moldSubmit()
                    },1000)
                }
            })
            return false
        }
        if (diffTime>=0 || _this.data.questionInfo2.question_info.type==2){
            // console.log(durTime,'durTime')
            // 考试未结束
            let days, hours, minutes, seconds, time_text;
            days = Math.floor(durTime  / 60 / 60 / 24);
            hours = Math.floor(durTime  / 60 / 60 % 24);
            minutes = Math.floor(durTime  / 60 % 60);
            seconds = Math.floor(durTime  % 60);
            seconds = seconds < 10 ? "0" + seconds : seconds
            minutes = minutes < 10 ? "0" + minutes : minutes
            hours = hours < 10 ? "0" + hours : hours

            time_text = hours + "小时" + minutes + "分" + seconds + '秒'

            wx.setNavigationBarTitle({
                title: time_text,
                success: (result) => {
                },
                fail: () => {
                },
                complete: () => {
                }
            });

            _this.setData({
                countdown: time_text,
                durTime:durTime-=1,
                days,
                hours,
                minutes,
                seconds
            })
            wx.setStorageSync(`mold_end_time_${report_id}`,_this.data.durTime)
            // console.log(that.data.countdown)
            //递归每秒调用countTime方法，显示动态时间效果
            setTimeout(() => {
                _this.countDown(this.data.reportId,_this.data.questionInfo.last_time)
            }, 1000);
        }else if (_this.data.questionInfo2.question_info.type==1){
            //考试结束
            this.setData({
                countdown: '考试已截止',
                jsq_no: false
            })
            wx.showToast({
                title:'考试已截止',
                icon:'none',
                success(res) {
                   setTimeout(()=>{
                       _this.moldSubmit()
                   },1000)
                }
            })
        }

    },
    //提交试卷
    moldSubmit() {
     
      console.log("66666666666666666666666666663");
      console.log(this.data.questionList);
      console.log("99999999999999999999999999999");
      /******进行错题集分类*/
      let wrong_list=[];
      wrong_list=this.data.questionList;

      

        const _this = this;
        /*****错题本
        wx.$request(wx.$api.make_wrong_logs, {
            wid:3,
            subject_data: wrong_list
        }).then(res => {
              console.log(res);
        })
        ******/
       /****选择题提交 */

       let state = 1;
        if (this.data.optionJson.length) {
            let isTrueList = this.data.optionJson.filter(item => item.is_correct != item.is_choice)
            state = isTrueList.length ? 3 : 2
        }

       if ((this.data.questionList[this.data.num].type == 1 ||this.data.questionList[this.data.num].type == 2) && this.data.optionJson.length) {
        this.mk_submit_subject(this.data.questionList[this.data.num].id, JSON.stringify(this.data.optionJson), state)

    }



        
        wx.setStorageSync(`mold_end_time_${this.data.reportId}`,'')
        wx.$request(wx.$api.mk_submit_member_report, {
            question_id: this.data.questionInfo.question_id,
            reportId:this.data.reportId
        }).then(res => {
            wx.showToast({
                title: '提交成功',
                icon: 'none',
                success(res) {
                  
                    setTimeout(() => {
                        wx.redirectTo({
                            url: `/mold-test/pages/examreport_mock/examreport?id=${_this.data.reportId}`
                        })
                    }, 1000)
                    
                }
            })
        })
        
    },
    mk_question_info(){
      wx.$request(wx.$api.mk_question_info,{
          report_id: this.data.reportId,
          question_id:this.data.questionInfo.question_id
      }).then(res=>{

          console.log(res,'题库信息的似的是的');
          this.setData({
              questionInfo2:res
          },()=>{
              this.countDown(this.data.reportId,this.data.questionInfo.last_time)

          })
      })
    },
    //获取答题卡信息
    get_mk_sheet_info() {
       let _this=this;
        wx.$request(wx.$api.mk_sheet_info, {
            report_id: _this.data.reportId
        }).then(res => {


          console.log("888888888888888888");//
          console.log(res);

          console.log("9999999999999999");
          
          

            if (res.list[0].type === 3) {
                this.setData({
                    showBigMask: true
                })
            }
            res.list.forEach(item=>{
                item.is_do = false
            })

           
            console.log("qqqqqqqqqqqqqqqqqqqqqqqqqq",res.list);
             var len = res.list.length;
             for (var i = 0; i < len; i++)
            {
              if(res.list[i].type==1 || res.list[i].type==2){ //单选，多选
                var lll=res.list[i].option_json.length;
                for(var ii=0;ii<lll;ii++){
                      if(res.list[i].option_json[ii].is_choice==1){ //代表已做
                        res.list[i].is_do=true;
                      }
                }
             }
             }
            

            this.setData({
                questionInfo: res.member_report_info,
                durTime:res.member_report_info.examination_s,
                questionList: res.list,
            },()=>{
               this.mk_question_info()
            })
            

            
             
            

        })
    },
    closeMoreMask() {
        this.setData({
            showMoreMask: false,
            showBigMask: false
        })
    },
    get_paperInfo(mid) {
        let params = {
            mock_class_id: mid
        }
        wx.$http.get(wx.$get.examination_mock_paperInfo, params).then(mock_res => {
            this.setData({
                paperInfo: mock_res
            })
            this.setData({
                jsq_no: true
            })
            this.setData({
                card: true
            })
            // if(mock_res.mock_type == 1){
            //   this.setData({
            //     card:true
            //   })
            // }
            params = {
                mock_class_id: mock_res.id,
                member_id: wx.$cache.get('member_id'),
            }
            // 上送考试及判断时间
            wx.$http.post(wx.$post.mock_log_add, params).then(log_res => {
                log_res.end_time = log_res.end_time * 1000
                if (log_res.status == 2 || this.getNowTime() >= log_res.end_time) {
                    console.log('API返回考试已结束');
                    this.jiao(true)
                    return false
                }
                wx.setStorageSync('mock_end_time_' + mock_res.id, log_res.end_time)
                this.countdown(mock_res.id, mock_res.mock_duration)
            })
        }).catch(error => {
            wx.showToast({
                title: error,
                icon: 'none',
                image: '',
                duration: 1500,
                mask: false,
                success: (result) => {

                },
                fail: () => {
                },
                complete: () => {
                }
            });
            // setTimeout(() => {
            //   wx.navigateBack({
            //     delta: 1
            //   });
            // }, 1000);
        })
    },
    /**
     * 倒计时
     * @param {*} paperInfo_id 试卷ID
     * @param {*} paperInfo_lang 试卷考试时长
     */
    countdown(paperInfo_id, paperInfo_lang) {
        if (!this.data.jsq_no) {
            return false
        }
        let now = new Date().getTime();
        let endDate = this.data.endDate;
        let end = new Date(endDate).getTime(); //设置截止时间
        let endTime = wx.getStorageSync('mock_end_time_' + paperInfo_id);
        if (endTime) {
            // console.log('非首次');
            // 计算以缓存开始时间加上考试时长得到的结束时间
            end = endTime
        } else {
            // console.log('首次');
            // 计算以当前时间加上考试时长得到的结束时间
            end = now + (paperInfo_lang * 60 * 1000)
            // 将当前时间作为结束时间缓存
            wx.setStorageSync('mock_end_time_' + paperInfo_id, end);
        }
        let days, hours, minutes, seconds, time_text;
        let that = this;
        let leftTime = end - now; //时间差
        if (leftTime >= 0) {
            days = Math.floor(leftTime / 1000 / 60 / 60 / 24);
            hours = Math.floor(leftTime / 1000 / 60 / 60 % 24);
            minutes = Math.floor(leftTime / 1000 / 60 % 60);
            seconds = Math.floor(leftTime / 1000 % 60);
            seconds = seconds < 10 ? "0" + seconds : seconds
            minutes = minutes < 10 ? "0" + minutes : minutes
            hours = hours < 10 ? "0" + hours : hours

            time_text = hours + "小时" + minutes + "分" + seconds + '秒'

            wx.setNavigationBarTitle({
                title: time_text,
                success: (result) => {
                },
                fail: () => {
                },
                complete: () => {
                }
            });

            that.setData({
                countdown: time_text,
                days,
                hours,
                minutes,
                seconds
            })
            // console.log(that.data.countdown)
            //递归每秒调用countTime方法，显示动态时间效果
            setTimeout(() => {
                that.countdown(paperInfo_id, paperInfo_lang)
            }, 1000);
        } else {
            console.log('考试结束');
            this.jiao(true)
            that.setData({
                countdown: '考试已截止',
                jsq_no: false
            })
        }
    },
    record(zid, tid, kid) {//从正常章节进来的题卡信息
        let params = {
            library_id: tid || '',
            course_id: kid || '',
            chapter_id: zid || '',
        }
        wx.$http.get(wx.$get.card_subject, params).then(res => {

            let ress = res
            let daitem = [
                {name: '单选题', children: []},
                {name: '多选题', children: []},
                {name: '阅读多问题', children: []},
                {name: '翻译题', children: []},
                {name: '分析题', children: []},
                {name: '作文题', children: []},
                {name: '大题', children: []},
            ]
            for (let i = 0; i < ress.length; i++) {
                ress[i].index = i + 1
                if (ress[i].type == 1) {
                    daitem[0].children = daitem[0].children.concat(res[i])
                }
                if (ress[i].type == 2) {
                    daitem[1].children = daitem[1].children.concat(res[i])
                }
                if (ress[i].type == 3) {
                    daitem[2].children = daitem[2].children.concat(res[i])
                }
                if (ress[i].type == 4) {
                    daitem[3].children = daitem[3].children.concat(res[i])
                }
                if (ress[i].type == 5) {
                    daitem[4].children = daitem[4].children.concat(res[i])
                }
                if (ress[i].type == 6) {
                    daitem[5].children = daitem[5].children.concat(res[i])
                }
            }
            this.setData({
                daitem: daitem
            })
            console.log(daitem, '答题卡信息')
        })
    },
    type1items(zid, tid, kid) {//章节列表进来的题id
        let params = {
            member_id: wx.$cache.get('member_id'),
            library_id: tid || '',
            course_id: kid || '',
            chapter_id: zid || ''
        }
        wx.$http.get(wx.$get.subject_ids, params).then(res => {
            console.log(res, '章节列表进来的所有题id')
            let num = 0
            res.forEach(item => {
                if (item.is_subject_log == 1) {
                    num++
                }

            })
            console.log(num, '做题')
            let ress = []
            for (let i = 0; i < res.length; i++) {
                ress = ress.concat(res[i].id)
            }
            this.setData({
                items: ress
            })
            this.tidetail()
        })
    },
    examination(mock_class_id) {//获取考试所有id
        let params = {
            mock_class_id: mock_class_id
        }
        wx.$http.get(wx.$get.examination_mock, params).then(res => {
            console.log(res, '考试列表')
            let ress = res
            let items = [] //所有题目id
            let daitem = [
                {name: '单选题', children: []},
                {name: '多选题', children: []},
                {name: '阅读多问题', children: []},
                {name: '翻译题', children: []},
                {name: '分析题', children: []},
                {name: '作文题', children: []},
                {name: '大题', children: []},
            ]
            for (let i = 0; i < ress.length; i++) {
                console.log('res的值', res[i]);
                ress[i].index = i + 1
                // ress[i].subject_log = []
                if (ress[i].type == 1) {
                    daitem[0].children = daitem[0].children.concat(res[i])
                }
                if (ress[i].type == 2) {
                    daitem[1].children = daitem[1].children.concat(res[i])
                }
                if (ress[i].type == 3) {
                    daitem[2].children = daitem[2].children.concat(res[i])
                }
                if (ress[i].type == 4) {
                    daitem[3].children = daitem[3].children.concat(res[i])
                }
                if (ress[i].type == 5) {
                    daitem[4].children = daitem[4].children.concat(res[i])
                }
                if (ress[i].type == 6) {
                    daitem[5].children = daitem[5].children.concat(res[i])
                }
                if (ress[i].type == 7) {
                    daitem[6].children = daitem[6].children.concat(res[i])
                }
            }
            for (let i = 0; i < ress.length; i++) {
                items = items.concat(ress[i].id)
            }
            this.setData({
                items,
                items2: ress,
                daitem
            })
            console.log('题卡信息', this.data.daitem);
            console.log('items的信息', this.data.items);
            console.log('num的信息', this.data.num);
            this.tidetail()
        }).catch(error => {
            wx.showToast({
                title: error,
                icon: 'none',
                image: '',
                duration: 1500,
                mask: false,
                success: (result) => {

                },
                fail: () => {
                },
                complete: () => {
                }
            });
            setTimeout(() => {
                wx.navigateBack({
                    delta: 1
                });
            }, 1000);
        })
    },
    wrongTopic() {//错题本的所有id
        let type = 2
        let params = {
            // library_ids: tid || '',
            // course_ids: kid || '',
            // chapter_ids: zid || '',
            page: 1,
            page_size: 300,
            type
        }
        wx.$http.post(wx.$get.mock_wrong_log_my, params).then(res => {
            console.log(res, '错题本所有id')
            for (var i = 0; i < res.length; i++) {
                if (!res[i].id) {
                    res.splice(i, 1);
                }

            }
            let items = []
            for (let i = 0; i < res.length; i++) {
                items = items.concat(res[i].id)
            }
            console.log('错题本来的所有：', items);
            // let daitem = [
            //   {name:'单选题',children:[]},
            //   {name:'多选题',children:[]},
            //   {name:'阅读多问题',children:[]},
            //   {name:'翻译题',children:[]},
            //   {name:'分析题',children:[]},
            //   {name:'作文题',children:[]},
            // ]
            // for(let i = 0;i<ress.length;i++){
            //   ress[i].index = i+1
            //   ress[i].subject_log = []
            //   if(ress[i].type==1){
            //     daitem[0].children =  daitem[0].children.concat(res[i])
            //   }
            //   if(ress[i].type==2){
            //     daitem[1].children =  daitem[1].children.concat(res[i])
            //   }
            //   if(ress[i].type==3){
            //     daitem[2].children =  daitem[2].children.concat(res[i])
            //   }
            //   if(ress[i].type==4){
            //     daitem[3].children =  daitem[3].children.concat(res[i])
            //   }
            //   if(ress[i].type==5){
            //     daitem[4].children =  daitem[4].children.concat(res[i])
            //   }
            //   if(ress[i].type==6){
            //     daitem[5].children =  daitem[5].children.concat(res[i])
            //   }
            // }
            this.setData({
                items,
                num: 0
            })
            this.tidetail()
        })
    },
    //获取选择信息
    getOptionJson(e) {
        this.setData({
            optionJson: e.detail,
            [`questionList[${this.data.num}].option_json`]:e.detail
        })
    },
    tidetail() {//题目解析
        console.log('题目ID', this.data.items[this.data.num]);
        let params = {
            member_id: wx.$cache.get('member_id'),
            subject_id: this.data.items[this.data.num]
        }
        wx.$http.get(wx.$get.mock_subject_info, params).then(res => {
            console.log(res, '题目解析')
            if (this.data.type == 1 && wx.$cache.get('answer')) {
                this.setData({
                    vague: true
                })
            }
            if (res.subject_log) {//表示这道题已经做过了，并且是正常章节进来的，直接显示答案
                console.log('做过了', res);
                this.setData({
                    detail: res
                })
                let my_answer = []//我选的答案
                if (res.type == 3 || res.type == 5) {//多问题的答案是数组，需要转过来
                    my_answer = JSON.parse(res.subject_log.my_answer)
                    console.log(my_answer, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
                    this.setData({
                        my_answer,
                        submit: false,
                    })
                } else {
                    my_answer = res.subject_log.my_answer.split(',')
                    this.setData({
                        submit: false,
                        my_answer
                    })
                }
            }
            if (this.data.type == 2) {//为考试需要单独处理数组//需要记录一下选择的问题
                if (res.type == 1 || res.type == 2) {
                    this.setData({//保存这到题的正确答案，交卷的时候比对
                        [`items2[${this.data.num}].correct_answer`]: res.correct_answer,
                        [`items2[${this.data.num}].fraction_total`]: res.fraction_total,//这道题一共多少分
                    })
                    if (this.data.items2[this.data.num].subject_log.length != 0) {//单选多选处理
                        for (let i = 0; i < this.data.items2[this.data.num].subject_log.my_answer.length; i++) {
                            for (let j = 0; j < res.option_str.length; j++) {
                                if (this.data.items2[this.data.num].subject_log.my_answer[i] == res.option_str[j].option) {
                                    res.option_str[j].flage = true
                                }
                            }
                        }
                    }
                }
                if (res.type == 4 || res.type == 6 || res.type == 7) {
                    this.setData({//保存这到题的正确答案，交卷的时候比对
                        [`items2[${this.data.num}].correct_answer`]: res.fraction_total,
                        [`items2[${this.data.num}].fraction_total`]: res.fraction_total,
                    })
                    if (this.data.items2[this.data.num].fen) {//自己填分处理
                        res.my_answer = this.data.items2[this.data.num].fen
                    }
                }
                if (res.type == 3 || res.type == 5) {
                    this.setData({
                        [`items2[${this.data.num}].my_answerlength`]: res.little_question_json.length
                    })
                }
                this.setData({
                    detail: res,
                    [`items2[${this.data.num}].type`]: res.type,//记录这道题是什么题
                })
            } else {
                this.setData({
                    detail: res
                })
            }
            this.pinglist()
            this.bilist()
        })
    },
    goye() { //夜间模式的切换
        this.setData({
            ye: !this.data.ye
        })
        if (this.data.ye) {
            wx.setNavigationBarColor({
                frontColor: '#ffffff',
                backgroundColor: '#202020',
                animation: {
                    duration: 400,
                    timingFunc: 'easeIn'
                }
            })
        } else {
            wx.setNavigationBarColor({
                frontColor: '#000000',
                backgroundColor: 'white',
            })
        }
    },
    show() { //答题卡显示出来
       
      console.log("34343434");

        if (this.data.type == 1) {//当只有type==1时答题卡才调用刷新题卡信息
            this.record(this.data.zid, this.data.tid, this.data.kid)
        }
        this.setData({
             show: true
        })
    },
    pinglist() {//评论列表
        let params = {
            member_id: wx.$cache.get('member_id'),
            subject_id: this.data.items[this.data.num],
            page: 1,
            page_size: 3
        }
        wx.$http.get(wx.$get.comment_list, params).then(res => {
            console.log(res, '评论列表')
            this.setData({
                comment: res
            })
        })
    },
    zhan(e) { //评论点赞
        const {
            id, type
        } = e.currentTarget.dataset
        var params = {
            log_id: id,
            type
        }
        wx.$http.get(wx.$get.give_log, params).then(res => {
            console.log(res, '点赞')
            if (type == 2) {
                this.pinglist()
            }
            if (type == 1) {
                this.bilist()
            }
        })
    },
    gocomment() {//跳转评论列表
        wx.navigateTo({
            url: `/pages/comment/comment?id=${this.data.items[this.data.num]}`,
        })
    },
    bilist() {//笔记列表
        let params = {
            member_id: wx.$cache.get('member_id'),
            subject_ids: this.data.items[this.data.num],
            // course_id:this.data.detail.course_id,
            // chapter_id:this.data.detail.chapter_id,
            // library_id:this.data.detail.library_id,
            page: 1,
            page_size: 3
        }
        wx.$http.get(wx.$get.note_list, params).then(res => {
            console.log(res, '笔记列表')
            this.setData({
                subject: res,
                reque: false,
            })
        })
    },
    cha() { //查看全部笔记
        wx.navigateTo({
            url: '/pages/quanbj/quanbj?id=' + this.data.items[this.data.num],
        })
    },
    gobaocuo() { //去我要报错页面
        app.title = this.data.detail.subject_str
        wx.navigateTo({
            url: '/pages/mistake/mistake?id=' + this.data.items[this.data.num],
        })
    },
    gomynote() {//跳转我的笔记
        wx.navigateTo({
            url: '/pages/myNotes/myNotes',
        })
    },
    gonewnote() {//跳转笔记列表
        wx.navigateTo({
            url: '/pages/newnote/newnote?id=' + this.data.items[this.data.num],
        })
    },
    submit() {//提交答案

      console.log("qqqqqqqqqqqqqqqqqq556565655656qqqqqqqqqqqqqqqqqqq");

        if (this.data.detail.type == 1 || this.data.detail.type == 2) {//单选多选
          
          console.log("wwwwwwwwwwww556565655656wwwwwwwwwwww");


            let detail = this.selectComponent('#exam').data.detail
            let my_answer = []//我选择的答案
            let answer = []//正确答案
            let is_correct = 2//是否正确1是2否
            for (let i = 0; i < detail.option_str.length; i++) {
                if (detail.option_str[i].is_correct == 1) {
                    answer = answer.concat(detail.option_str[i].option)
                }
                if (detail.option_str[i].flage) {
                    my_answer = my_answer.concat(detail.option_str[i].option)
                }
            }
            if (my_answer.length == 0) {
                wx.showToast({
                    title: '请选择答案',
                    icon: 'none'
                })
                return
            }
            if (my_answer.toString() == answer.toString()) {
                is_correct = 1
            }
            this.submitfang(my_answer, is_correct, '')//提交答案请求
        }
        if (this.data.detail.type == 4 || this.data.detail.type == 6) {//分析和翻译题
            let detail = this.selectComponent('#exam2').data
            let my_answer = detail.fen//我选择的答案
            this.submitfang(my_answer, 1, '')
        }
        if (this.data.detail.type == 7) {//大题
            console.log('大题');
            let detail = this.selectComponent('#exam7').data
            console.log(detail);
            let my_answer = detail.fen //我选择的分数
            let little_question_json = detail.my_answer //我输入的答案
            this.submitfang(my_answer, 1, little_question_json)
        }
        if (this.data.detail.type == 3) {//阅读
            let my_answer = []//我选择的答案
            let is_correct = 2//是否正确1是2否
            let zheng = []//装所有正确答案
            let zheng2 = []//装所有选择的答案
            let detail = this.selectComponent('#exam3').data.detail
            for (let i = 0; i < detail.little_question_json.length; i++) {
                zheng = zheng.concat(detail.little_question_json[i].correct_answer)
                my_answer = my_answer.concat([{answer: ''}])
                for (let j = 0; j < detail.little_question_json[i].option_str.length; j++) {
                    if (detail.little_question_json[i].option_str[j].flage) {
                        zheng2 = zheng2.concat(detail.little_question_json[i].option_str[j].option)
                        my_answer[i].answer = detail.little_question_json[i].option_str[j].option
                    }
                }
            }
            if (zheng.length != zheng2.length) {
                wx.showToast({
                    title: '每个小问的答案都要选择',
                    icon: 'none'
                })
                return
            }
            if (zheng.toString() == zheng2.toString()) {
                is_correct = 1
            }
            my_answer = JSON.stringify(my_answer)
            this.submitfang(my_answer, is_correct, '')
        }
        if (this.data.detail.type == 5) {//卓文
            let detail = this.selectComponent('#exam3').data
            let my_answer = JSON.stringify(detail.fen2) //我选择的分数
            this.submitfang(my_answer, 1, '')
        }

    },
    submitfang(my_answer, is_correct, little_question_json) {//提交答案方法
        this.setData({
            reque: true,
        })
        console.log('保存答案', my_answer);
        let params = {
            subject_id: this.data.items[this.data.num],
            my_answer: this.data.detail.type != 7 ? my_answer.toString() : my_answer,
            member_id: wx.$cache.get('member_id'),
            is_correct,
            little_question_json: little_question_json,
            mock_class_id: this.data.paperInfo.id
        }
        wx.$http.get(wx.$get.mock_make_question, params).then(res => {
            console.log(res, '做题')
            if (this.data.type == 1) {
                if (this.data.num > this.data.questionNumber) {
                    this.setData({
                        questionNumber: this.data.num
                    })
                }
            }
            if (is_correct == 1 && this.data.type == 3) {
                if (this.data.num + 1 == this.data.items.length) {
                    wx.showToast({
                        title: '没有下一题了!',
                        icon: 'none'
                    })
                } else {
                    this.next()
                    return
                }
            }
            // if (wx.$cache.get('she') && this.data.type == 1 && is_correct == 1) {//答对了直接下一题
            //   if (this.data.num + 1 == this.data.items.length) {
            //     wx.showToast({
            //       title: '没有下一题了!',
            //       icon: 'none'
            //     })
            //   } else {
            //     this.next()
            //     return
            //   }
            // }
            if (wx.$cache.get('yin') && this.data.type == 1) {//做题播放音频
                if (is_correct == 1) {
                    this.zheng()
                }
                if (is_correct == 2) {
                    this.cuowu()
                }
            }
            if (this.data.detail.type == 3 || this.data.detail.type == 5 || this.data.detail.type == 7) {
                this.setData({
                    submit: false,
                    my_answer: JSON.parse(my_answer)
                })
            } else {
                if (this.data.type == 3) {
                    this.setData({
                        submit: true
                    })
                } else {
                    this.setData({
                        submit: false,
                        my_answer: my_answer
                    })
                }
            }
            this.setData({
                reque: false,
            })

            this.setData({
                daitem: this.data.daitem
            })

        }).catch(err => {
            this.setData({
                reque: false,
            })
        })
    },
    goxiaa(e) {//知识点
        console.log(e.currentTarget.dataset.index)
        app.globalData.content = this.data.detail.subject_knowledge[e.currentTarget.dataset.index].content
        wx.navigateTo({
            url: '/pages/waparse/waparse?title=' + this.data.detail.subject_knowledge[e.currentTarget.dataset.index].title + '&is_url=' + 1,
        })
    },
    nextMask() {
        this.setData({
            isNext: true
        }, () => {
            this.next()
        })
    },
    next(e) {//下一题
       this.setData({
        tabid:0
       });
        if (this.data.num + 1 === this.data.questionList.length) {
            wx.showToast({
                title: '已是最后一题',
                icon: 'none'
            })
            return false
        }
        //多选时只选了一体
        if (this.data.questionList[this.data.num].type == 2 && (this.data.optionJson.filter(item => item.is_choice == 1)).length == 1 && !this.data.isNext) {
            this.setData({
                showMoreMask: true
            })
            return false
        }

        let state = 1;
        if (this.data.optionJson.length) {
            let isTrueList = this.data.optionJson.filter(item => item.is_correct != item.is_choice)
            state = isTrueList.length ? 3 : 2
        }
        console.log(this.data.optionJson.filter(item => item.is_choice == 1).length,'length')
        if (this.data.optionJson.filter(item => item.is_choice == 1).length){
            this.setData({
                [`questionList[${this.data.num}].is_do`]:true
            })
        }
        //单选 多选
        if ((this.data.questionList[this.data.num].type == 1 ||this.data.questionList[this.data.num].type == 2) && this.data.optionJson.length) {
            this.mk_submit_subject(this.data.questionList[this.data.num].id, JSON.stringify(this.data.optionJson), state)

        } else {

        }
        // 已做
        this.setData({
            num: this.data.num += 1,
            submit: false,
            isNext: false,
            showMoreMask: false
        })

        console.log('yyyyyyyyyyyyyy');
        console.log(this.data.reportId,'998989rrrrrrrrrrrrrrrrrr');

        if (this.data.questionList[this.data.num].type == 3){
            wx.$request(wx.$api.mk_subject_info, {
                report_id:this.data.reportId,
                subject_id:this.data.questionList[this.data.num].subject_id
            }).then(res => {
                res.mk_ask.forEach(item => item.flage = false)
                console.log(res);
                this.setData({
                    subjectInfo: res,
                })
            })
        }
        console.log(this.data.num, this.data.questionList.length)
        if (this.data.questionList[this.data.num].type == 3) {
            this.setData({
                showBigMask: true
            })
        }
        // this.gun()
        // this.tidetail()


    },

    mk_submit_subject(sheet_id, option_json, state) {
        //sheet_id	1	是	string	答题卡记录id
        // option_json	[ { “is_correct”: 1, “content”: “选项内容1”, “is_choice”: 1 }, { “is_correct”: 2, “content”: “选项内容2”, “is_choice”: 2 }, { “is_correct”: 2, “content”: “选项内容3”, “is_choice”: 2 }, { “is_correct”: 2, “content”: “选项内容4”, “is_choice”: 2 } ]	是	string	选项类型(单选与多选时) (转数组后格式[ [ “is_correct”=>1,”content”=>”选项内容”,”is_choice”=>1] ] (is_correct是否为正确答案 1是 2否;content选项内容;is_choice 是否选择 1是 2否))
        // state	2	是	string	状态 1未做 2正确 3错误
        wx.$request(wx.$api.mk_submit_subject, {
            sheet_id,
            option_json,
            state
        }).then(res => {
            this.setData({
                optionJson: []
            })
        })
    },
    shang() {//上一题
        console.log(this.data.num)
        if (!this.data.num) {
            wx.showToast({
                title: '已是第一题',
                icon: 'none'
            })
            return false
        }
        this.setData({
            num: this.data.num -= 1,
            submit: false
        })
        this.gun()
        // this.tidetail()
    },
    zheng() { //正确音频
        var innerAudioContext = wx.createInnerAudioContext();
        audioPlay()

        function audioPlay() {
            innerAudioContext.src = wx.$cache.get('can').correct_music;
            innerAudioContext.play();
            console.log('1')
        }
    },
    cuowu() { //错误音频
        console.log('cuo')
        var innerAudioContext = wx.createInnerAudioContext();
        audioPlay2()

        function audioPlay2() {
            innerAudioContext.src = wx.$cache.get('can').error_music;
            console.log(wx.$cache.get('can').error_music)
            innerAudioContext.play();
            console.log('2')
        }
    },
    jiao(is_force) {//叫卷
        let {items2} = this.data
        let arr = []
        for (let i = 0; i < items2.length; i++) {
            if (items2[i].is_correct != 1) {
                arr = arr.concat(1)
            }
        }
        if (is_force) {
            app.items2 = items2
            app.items = this.data.items
            app.time2 = this.getNowTime()
            app.paperInfo = this.data.paperInfo
            // 请求交卷接口
            // this.mock_winding()
            this.setData({
                countdown: '考试已截止',
                jsq_no: false
            })
            wx.redirectTo({
                url: '/pages/examreport_mock/examreport?source=1'
            })
            return false
        }
        let tips = arr.length == 0 ? '你确定要交卷吗？' : '你还有' + arr.length + '道题没做,确定要交卷吗？'
        wx.showModal({
            title: '提示',
            content: tips,
            success: (res) => {
                if (res.confirm) {
                    app.items2 = items2
                    app.items = this.data.items
                    app.time2 = this.getNowTime()
                    app.paperInfo = this.data.paperInfo
                    // 请求交卷接口
                    // this.mock_winding()

                    wx.redirectTo({
                        url: '/pages/examreport_mock/examreport?source=1'
                    })
                }
            }
        })
        console.log(this.data.items2, '交卷的题')
    },
    // 获取当前时间
    getNowTime() {
        let dateTime
        let yy = new Date().getFullYear()
        let mm = new Date().getMonth() + 1
        let dd = new Date().getDate()
        let hh = new Date().getHours()
        let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes()
            :
            new Date().getMinutes()
        let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
            :
            new Date().getSeconds()
        dateTime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss
        console.log(dateTime)
        return dateTime
    },
    addjia(e) {//加入错题移除错题
        let {flage} = e.currentTarget.dataset
        if (flage == 2) {
            let params = {
                subject_id: this.data.items[this.data.num]
            }
            wx.$http.get(wx.$get.wrong_log_add, params).then(res => {
                console.log(res, '加入错题')
                this.setData({
                    'detail.is_wrong': 1
                })
            })
        } else {
            let params = {
                subject_id: this.data.items[this.data.num]
            }
            wx.$http.get(wx.$get.wrong_log_del, params).then(res => {
                console.log(res, '移除错题')
                this.setData({
                    'detail.is_wrong': 2
                })
            })
        }
    },
    gun() {//屏幕滚到最上面
        wx.pageScrollTo({
            scrollTop: 0
        });
    },
    tidetail2() {//题目解析只用来刷新当前评论笔记数量的
        let params = {
            member_id: wx.$cache.get('member_id'),
            subject_id: this.data.items[this.data.num]
        }
        wx.$http.get(wx.$get.subject_info, params).then(res => {
            console.log(res, '题目解析')
            this.setData({
                'detail.comment_num': res.comment_num,
                'detail.note_num': res.note_num
            })
            this.pinglist()
            this.bilist()
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.setData({
            jsq_no: false
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        this.setData({
            jsq_no: false
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            return {
                title: wx.$cache.get('fx').title,
                imageUrl: wx.$cache.get('fx').img, // 图片 URL
                path: `/pages/brushTopic/brushTopic?type=4&pid=${wx.$cache.get('member_id')}&id=${this.data.items[this.data.num]}`
            }
        } else {
            return {
                title: wx.$cache.get('fx').title,
                imageUrl: wx.$cache.get('fx').img,
                path: `/pages/index/index?pid=${wx.$cache.get('member_id')}`
            }
        }
    },
    onShareTimeline() {
        return {
            title: wx.$cache.get('fx').title,
            imageUrl: wx.$cache.get('fx').img,
            query: `a=${wx.$cache.get('member_id')}`,
        }
    }
})
